<?php
declare (strict_types = 1);

namespace app\service\logic\backend\region;

use app\service\logic\BaseService;
use think\Model;
use think\db\exception\DbException;
use app\model\communal\RegionModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

final class RegionService extends BaseService
{
    protected string $modelClassName = 'RegionModel';

    /**
     * 下拉菜单无分页
     *
     * @param $params
     * @param array $search_fields
     * @param array $search
     * @param string $label
     * @param string $value
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getOptions($params, $search_fields = [], $search = [], $label = 'name', $value = 'id')
    {
        $isSearch = $params['search'] ?? false;
        $isClear = $params['clear'] ?? false;
        $order = $this->orderByParams($params);

        $options = RegionModel::field(RegionModel::$column)
            ->withSearch($search_fields, $search)
            ->order($order)
            ->select()
            ->toArray();

        return $this->amisOptions($options, 'name', 'code', $isSearch, $isClear);
    }

    public function orderByParams($params, string $column = 'id', string $type = 'desc')
    {
        return parent::orderByParams($params, 'code', 'asc');
    }

    public function getTreeByParentColumn($children, int $parent = 0, string $childColumn = 'id', string $parentColumn = 'pid')
    {
        return parent::getTreeByParentColumn($children, $parent, 'code', 'p_code');
    }

    /**
     * @param $name
     * @return mixed
     */
    public function getCodeByName($name)
    {
        return RegionModel::where('name', 'like', $name . '%')->value('code');
    }
}
